import { NextResponse } from "next/server";
import roleModule from "@/modules/role";
import userModule from "@/modules/user";
import { AUTH_TOKEN } from "@/config/settings";
import jwt from '@/utils/jwt'

export async function GET(request) {
  const codeMap = { 0: '查询全部角色成功', 1: '查询角色失败' }
  const id = request.nextUrl.searchParams.get('id');
  if (id) {
    const data = await roleModule.get(Number(id));
    if (!data) {
      return NextResponse.json({ code: 1, codeMap, message: "Role not found", data: null }, { status: 404 })
    } else {
      return NextResponse.json({ code: 0, codeMap, message: "Success", data: data }, { status: 200 })
    }
  }
  const data = await roleModule.getAll();
  if (!data) {
    return NextResponse.json({ code: 1, codeMap, message: "Role not found", data: null }, { status: 404 })
  } else {
    return NextResponse.json({ code: 0, codeMap, message: "Success", data: data }, { status: 200 })
  }
}

export async function PUT(request) {
  const codeMap = { 0: '更新成功', 1: '登录验证失败', 2: '用户不存在', 3: 'Code必须是唯一的，请更换Code', 4: '服务器错误' };
  const { id, name, description, code, permissions } = await request.json();
  const token = request.cookies.get(AUTH_TOKEN)?.value;
  if (!token) return NextResponse.json({ code: 1, codeMap, message: 'Invalid token' }, { status: 401 });
  try {
    const payload = await jwt.verify(token);
    if (!payload) return NextResponse.json({ code: 1, codeMap, message: 'Invalid token' }, { status: 401 });
    const changeRole = await roleModule.getById(id);
    if (!changeRole) return NextResponse.json({ code: 2, codeMap, message: 'Role not found' }, { status: 404 });
    const isHasCode = await roleModule.getByCode(code);
    if (isHasCode && isHasCode?.id !== id && isHasCode?.code === code) return NextResponse.json({ code: 3, codeMap, message: 'Code already exists' }, { status: 409 });
    await roleModule.updateAll(id, name, description, code, permissions);
    return NextResponse.json({ code: 0, codeMap, message: 'Success' });
  } catch (e) {
    return NextResponse.json({ code: 4, codeMap, message: 'server error' }, { status: 500 });
  }
}

export async function POST(request) {
  const codeMap = { 0: '添加成功',1: '名称不能为空', 2: 'Code不能为空', 3: 'Code必须是唯一的，请更换Code', 4: 'Permissions必须是数组', 5: 'Permissions不能为空', 6: '服务器错误'};
  const { name, description, code, permissions } = await request.json();
  try {
    if (!name) return NextResponse.json({ code: 1, codeMap, message: 'Name is required' }, { status: 400 });
    if (!code) return NextResponse.json({ code: 2, codeMap, message: 'Code is required' }, { status: 400 });
    const isHasCode = await roleModule.getByCode(code);
    if (isHasCode) return NextResponse.json({ code: 3, codeMap, message: 'Code already exists' }, { status: 409 });
    if (!Array.isArray(permissions)) return NextResponse.json({ code: 4, codeMap, message: 'Permissions must be an array' }, { status: 400 });
    if (permissions.length === 0) return NextResponse.json({ code: 5, codeMap, message: 'Permissions cannot be empty' }, { status: 400 }); 
    const res = await roleModule.insertIncludePermissions(name, description, code, permissions);
    if (!res.roleId || res?.insertRolePermissionResult?.affectedRows === 0) return NextResponse.json({ code: 6, codeMap, message: 'Server error' }, { status: 500 });
    return NextResponse.json({ code: 0, codeMap, message: 'Success' });
  } catch (e) {
    return NextResponse.json({ code: 6, codeMap, message: 'server error' }, { status: 500 });
  }
}

export async function DELETE(request) {
  const codeMap = { 0: '删除成功', 1: '登录验证失败', 2: 'Id不存在或传入格式错误', 3: '角色不存在', 4: '角色已经被用户使用，请先删除用户或是给用户更换角色', 5: '删除失败', 6: '服务器错误' };
  const ids = await request.json();
  const token = request.cookies.get(AUTH_TOKEN)?.value;
  if (!token) return NextResponse.json({ code: 1, codeMap, message: 'Invalid token' }, { status: 401 });
  try {
    const payload = await jwt.verify(token);
    if (!payload) return NextResponse.json({ code: 1, codeMap, message: 'Invalid token' }, { status: 401 });
    if (!ids || ids.length === 0) return NextResponse.json({ code: 2, codeMap, message: 'Invalid ids' }, { status: 400 });
    const getRoles = await roleModule.getById(ids);
    if (getRoles.length !== ids.length) return NextResponse.json({ code: 3, codeMap, message: 'Role not found' }, { status: 404 });
    const userCount = await userModule.getUsersCountByRoles(ids);
    if (userCount > 0) return NextResponse.json({ code: 4, codeMap, message: 'Role is used by users' }, { status: 409 });
    const res = await roleModule.deleteById(ids);
    if (res.affectedRows === 0) return NextResponse.json({ code: 5, codeMap, message: '删除失败' }, { status: 404 });
    return NextResponse.json({ code: 0, codeMap, message: 'Success' });
  } catch (e) {
    return NextResponse.json({ code: 6, codeMap, message: 'Server error' }, { status: 500 });
  }
}